# -*- coding:utf-8 -*-

from flask import request, render_template, jsonify, session, current_app
from app import db
from app.models.account import User, Freeze, Upgrade
from app.models.log import UserLog
from app.models.application import Business_Application as BA, Purchase_Application as PA
from app.tools.permission import permission
from app.tools.log import log
from app.tools.redis_op import Operator
from app.tools.number import get_number
from app.tools.safe import safe_data
from flask_login import login_required
import datetime
from . import outside


@outside.before_request
@login_required
@permission(['service', 'director', 'review', 'admin', 'super'])
def check_permission():			#检查权限
	return


@outside.route('/individual/list/')
def individual_list():			#只返回个人账户的页面，相关数据由ajax异步获取
	return render_template('account/outside/individual.html')


@outside.route('/company/list/')
def company_list():			#只返回商家账户的页面，相关数据由ajax异步获取
	return render_template('account/outside/company.html')


@outside.route('/get_user_list/')
def get_user_list():			#获取用户列表，不同的用户类型通过user_type区分
	values = request.values
	limit = int(values.get('limit', '10'))
	offset = int(values.get('offset', '0'))
	state = values.get('state')		#账户状态
	user_type = values.get('user_type')	#用户类型，商家、个人
	number = values.get('number')		#用户编号
	start = values.get('start')		
	end = values.get('end')			
	area = values.get('area')		
	search_type = values.get('search_type')
	tb_name = values.get('tb_name')		#前端页面中多个表格共用同一组搜索参数，tb_name用于标识当前是哪一个表格在使用这些参数
	if state is None or user_type is None:
		return jsonify({'state': -1, 'msg': u'参数不全'})
	try:	#将时间参数转为datetime格式
		start = datetime.datetime.strptime(start, '%Y-%m-%d')
		end = datetime.datetime.strptime(end, '%Y-%m-%d')
		end = end + datetime.timedelta(days=1)	#需要加一天才可以搜索到原本的end指定的日期
	except ValueError:
		return jsonify({'state': 1, 'msg': u'参数错误'})
	data = []
	kw = {}
	list_type = {'0': 'valid', '1': 'invalid', '2': 'review'}	
	if state != '2':	#个人用户及已经通过审批的商家用户
		result = User.query
		kw['user_type'] = user_type
		kw['account_state'] = state
		if tb_name == list_type[state] and search_type != '4':	#4代表重置搜索，即不考虑搜索条件；tb_name用于检查当前的搜索参数是否与表格相对应
			if search_type == '0':
				kw['user_number'] = number
			if search_type == '1' or search_type == '3':
				result = result.filter(User.area.like('%'+area+'%'))
			if search_type == '2' or search_type == '3':
				result = result.filter(User.register_date.between(start, end))
		result = result.filter_by(**kw).order_by(db.desc(User.register_date)).paginate(offset/limit+1, limit, False)
		count = result.total
		if user_type == '1':	#商家用户
			types = {'0': u'平台注册', '1': u'个人升级', '2': u'商家修改信息'}	#商家用户的注册类型
			for item in result.items:
				data.append({
					'user_number': item.user_number,
					'company_name': item.company_name,
					'company_tel': item.company_tel,
					'corporation_name': item.corporation_name,
					'time': item.register_date.strftime("%Y-%m-%d %H:%M:%S"),
					'area': item.area,
					'register_type': types[str(item.register_type)],
					'operate': item.user_number,
				})
		else:	#个人用户
			for item in result.items:
				data.append({
					'user_number': item.user_number,
					'phone': item.phone,
					'name': item.name,
					'time': item.register_date.strftime("%Y-%m-%d %H:%M:%S"),
					'area': item.area,
					'operate': item.user_number,
				})
	else:	#待审批的商家用户
		result = Upgrade.query
		kw['state'] = 0
		if tb_name == list_type[state] and search_type != '4':
			if search_type == '0':
				kw['number'] = number
			if search_type == '1' or search_type == '3':
				result = result.filter(Upgrade.area.like('%'+area+'%'))
			if search_type == '2' or search_type == '3':
				result = result.filter(Upgrade.submission_date.between(start, end))
		result = result.filter_by(**kw).order_by(db.desc(Upgrade.submission_time)).paginate(offset/limit+1, limit, False)
		count = result.total
		types = {'0': u'平台注册', '1': u'个人升级', '2': u'商家修改信息'}	#商家用户的注册类型
		for item in result.items:
			data.append({
				'number': item.number,
				'company_name': item.company_name,
				'company_tel': item.company_tel,
				'corporation_name': item.corporation_name,
				'submission_time': item.submission_time.strftime("%Y-%m-%d %H:%M:%S"),
				'area': item.area,
				'application_type': types[str(item.application_type)],
				'operate': item.number,
			})

	json = {'total': count, 'rows': data}
	return jsonify(json)

@outside.route('/details/')
def details():		#账户的详细信息页
	number = request.values.get('number')
	if number:
		user = User.query.filter_by(user_number=number).first()
		if user:
			if user.user_type == 1:
				return render_template('account/outside/cmp_detail.html', user=user, uid=user.id, domain=current_app.config['QINIU_DOMAIN'])
			else:
				return render_template('account/outside/idv_detail.html', user=user, uid=user.id)		
	return render_template('404.html'), 404

@outside.route('/freeze/', methods=['GET', 'POST'])
def freeze():		#冻结账户
	number = request.values.get('number')	#冻结账号
	reason = request.values.get('reason')	#冻结原因
	if number is None or reason is None:	
		return jsonify({'state': -1, 'msg': u'参数不全'})
	if reason == "":
		return jsonify({'state': 1, 'msg': u'请填写冻结原因'})
	user = User.query.filter_by(user_number=number).filter(User.account_state!=1).first()
	if not user:
		return jsonify({'state': 1, 'msg': u'用户不存在'})
	user.account_state = 1	#冻结状态
	user.save()
	op = Operator()
	op.lpush('invalid_id', user.id)
	data = {}
	data['user_id'] = user.id
	data['freeze_id'] = session.get('sid')
	data['freeze_name'] = session.get('name')
	data['reason'] = reason 
	data['freeze_time'] = datetime.datetime.now()
	data = safe_data(data)
	record = Freeze(**data)	#记录冻结信息
	record.save()
	log(u'冻结账户%s'%user.user_number)
	return jsonify({'state': 0})
	
@outside.route('/recovery/', methods=['GET', 'POST'])
def recovery():		#解冻账户
	number = request.values.get('number')
	if not number:	
		return jsonify({'state': -1, 'msg': u'参数不全'})
	user = User.query.filter_by(user_number=number, account_state=1).first()
	if not user:
		return jsonify({'state': 1, 'msg': u'用户不存在'})
	user.account_state = 0
	user.save()
	op = Operator()
	op.lrem('invalid_id', 0, user.id)
	result = Freeze.query.filter_by(user_id=user.id, recovery_time=None).first()	#找出之前的冻结记录，加入解冻的相关信息
	if result:
		result.recovery_time = datetime.datetime.now()
		result.recovery_id = session.get('sid')
		result.recovery_name = session.get('name')
		result.save()
	log(u'恢复账户%s'%user.user_number)
	return jsonify({'state': 0})

@outside.route('/details/get_list/')
def get_details_list():		#详情页中相关表格的数据
	limit = int(request.values.get('limit', '10'))
	offset = int(request.values.get('offset', '0'))
	list_type = request.values.get('list_type')	#表格的类型
	uid = request.values.get('uid')
	if list_type is None or uid is None:
		return jsonify({'state': -1, 'msg': u'参数不足'})
	if list_type == 'buy':	#购车申请的表格
		result = PA.query.filter_by(applicant_id=uid).order_by(db.desc(PA.submission_date)).paginate(offset/limit+1, limit, False)
	elif list_type in ['rent', 'finance', 'service']:	#业务申请的表格
		result = BA.query.filter_by(applicant_id=uid, application_type=list_type).order_by(db.desc(BA.submission_date)).paginate(offset/limit+1, limit, False)
	elif list_type == 'invalid':	#违规记录的表格
		result = Freeze.query.filter_by(user_id=uid).order_by(db.desc(Freeze.freeze_time)).paginate(offset/limit+1, limit, False)
	elif list_type == 'operation':	#操作记录的表格
		result = UserLog.query.filter_by(user_id=uid).order_by(db.desc(UserLog.time)).paginate(offset/limit+1, limit, False)
	else:
		return jsonify({'state': 2, 'msg': u'参数错误'})
	count = result.total
	data = []
	states = {0: u'待分配', 1: u'待跟进', 2: u'跟进中', 3: u'线下跟进', 4: u'已废弃'}
	if list_type in ['buy', 'rent', 'finance', 'service']:	#不同类型的表格返回不同的数据
		for item in result.items:
			operate = '/details/?app_number=%s&app_type=%s' % (item.number, list_type)
			if list_type == 'buy' and item.outside:
				operate = '/outside/?app_number=%s' % item.number
			data.append({
				'number': item.number,
				'title': item.car_title if list_type == 'buy' else item.product,
				'phone': item.phone,
				'time': item.submission_date.strftime("%Y-%m-%d %H:%M:%S"),
				'area': item.area,
				'state': states[item.state],
				'operate': operate,
			})
	elif list_type == 'invalid':
		for item in result.items:
			data.append({
				'freeze_time': item.freeze_time.strftime("%Y-%m-%d %H:%M:%S"),
				'freeze_name': item.freeze_name,
				'reason': item.reason,
				'recovery_name': item.recovery_name if item.recovery_name else '无',
				'recovery_time': item.recovery_time.strftime("%Y-%m-%d %H:%M:%S") if item.recovery_time else u'未恢复',
			})
	elif list_type == 'operation':
		for item in result.items:
			data.append({
				'ip': item.ip,
				'operator': item.name,
				'phone': item.phone,
				'operation': item.operation,
				'area': item.area,
				'time': item.time.strftime("%Y-%m-%d %H:%M:%S"),
			})
	json = {'total': count, 'rows': data}
	return jsonify(json)

@outside.route('/review/upgrade/')
@permission(['review', 'admin', 'super'])
def review_upgrade():		#返回商家注册申请的详情页
	number = request.values.get('number')
	if number is None:
		return render_template('404.html'), 404
	upgrade = Upgrade.query.filter_by(number=number, state=0).first()
	if not upgrade:
		return render_template('404.html'), 404
	user = ''
	if upgrade.application_type == 1:
		user = User.query.filter_by(id=upgrade.user_id).first()
		if not user:
			return render_template('404.html'), 404
	return render_template('account/outside/upgrade.html', upgrade=upgrade, user=user)

@outside.route('/review/pass/', methods=['GET', 'POST'])
@permission(['review', 'admin', 'super'])
def review_pass():		#通过商家注册申请
	number = request.values.get('number')
	if number is None:
		return jsonify({'state': -1, 'msg': u'参数不足'})
	ug = Upgrade.query.filter_by(number=number, state=0).first()
	if not ug:
		return jsonify({'state': 2, 'msg': u'对象不存在'})
	if ug.application_type == 0:	#初始注册
		data = {}
		data['name'] = ug.name
		data['phone'] = ug.phone
		data['address'] = ug.address
		data['company_name'] = ug.company_name
		data['company_tel'] = ug.company_tel
		data['company_address'] = ug.company_address
		data['corporation_name'] = ug.corporation_name
		data['intro'] = ug.intro
		data['business_license'] = ug.business_license
		data['contact_name'] = ug.contact_name
		data['contact_phone'] = ug.contact_phone
		data['user_number'] = get_number('WH')
		data['password_hash'] = ug.password
		data['register_type'] = 0
		data['register_date'] = datetime.datetime.now()
		data['account_state'] = 0
		data['user_type'] = 1
		data = safe_data(data)
		user = User(**data)
		user.save()
		ug.state = 1	#将申请置为已通过状态
		ug.save()
		log(u'通过账户%s的商家注册申请'%user.user_number)
		return jsonify({'state': 0})
	else:	#个人升级或商家修改个人信息
		user = User.query.filter_by(id=ug.user_id).first()	#找出原有账户
		if not user:
			return jsonify({'state': 2, 'msg': u'对象不存在'})
		data['company_name'] = ug.company_name
		data['company_tel'] = ug.company_tel
		data['company_address'] = ug.company_address
		data['corporation_name'] = ug.corporation_name
		data['intro'] = ug.intro
		data['business_license'] = ug.business_license
		data['contact_name'] = ug.contact_name
		data['contact_phone'] = ug.contact_phone
		if ug.application_type == 1:	#个人升级为商家，需要记录升级时间
			data['upgrade_date'] = datetime.datetime.now()
			data['user_type'] = 1
		data = safe_data(data)
		user = User(**data)
		user.save()
		ug.state = 1	#将申请置为已通过状态
		ug.save()
		log(u'通过账户%s的商家注册申请'%user.user_number)
		return jsonify({'state': 0})
	return jsonify({'state': 5, 'msg': u'系统错误'})

@outside.route('/review/reject/', methods=['GET', 'POST'])
@permission(['review', 'admin', 'super'])
def review_reject():	#拒绝商家申请
	number = request.values.get('number')
	reason = request.values.get('reason')
	if number is None or reason is None:	
		return jsonify({'state': -1, 'msg': u'参数不全'})
	if reason == "":
		return jsonify({'state': 1, 'msg': u'请填写拒绝原因'})
	ug = Upgrade.query.filter_by(number=number, state=0).first()
	ug.reason = safe_data(reason)	#拒绝原因
	ug.state = 2	#将申请置为已拒绝状态
	ug.save()
	log(u'拒绝商家申请%s'%ug.number)
	return jsonify({'state': 0})

